package com.excesys.exsecs.energy.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.excesys.exsecs.common.core.util.R;
import com.excesys.exsecs.energy.entity.EnergyInput;
import com.excesys.exsecs.energy.service.EnergyInputService;
import com.excesys.exsecs.energy.vo.EnergyInputExceVo;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.Year;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.excesys.exsecs.energy.mapper.EnergyInputMapper;
/**
 * 通用能耗流水表
 *
 * @author zhang
 * @date 2024-09-10 14:40:46
 */
@Service
public class EnergyInputServiceImpl extends ServiceImpl<EnergyInputMapper, EnergyInput> implements EnergyInputService {
	@Override
	public R batchImport(List<EnergyInputExceVo> energyInputExceVos, BindingResult bindingResult) {
		return null;
	}

	@Override
	public List powerData(String unitNo, String energyType) {
		List list = new ArrayList<>();
		Map map = new HashMap<>();
		//本月
		YearMonth tomonth = YearMonth.from(LocalDate.now());
		Double monthPower = this.baseMapper.sumPowerList(energyType, unitNo, tomonth.toString().replaceAll("-", ""));
		map.put("monthPower", monthPower);
		//上月
		YearMonth lastMonth = YearMonth.from(LocalDate.now().minusMonths(1));
		Double lastMonthPower = this.baseMapper.sumPowerList(energyType, unitNo, lastMonth.toString().replaceAll("-", ""));
		// 环比增长率
		if (monthPower > 0) {
			Double growthRate = (monthPower - lastMonthPower) / lastMonthPower * 100; // 增长率
			if (Double.isInfinite(growthRate) || Double.isNaN(growthRate)) {
				map.put("monthRate", "-");
			} else {
				map.put("monthRate", new BigDecimal(String.valueOf(growthRate)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
			}
		} else {
			map.put("monthRate", "-");
		}
		//年
		Year toyears = Year.from(LocalDate.now());
		Double yearsPower = this.baseMapper.sumPowerList(energyType, unitNo, toyears.toString());
		map.put("yearsPower", yearsPower);
		//上月
		Year lastyears = Year.from(LocalDate.now().minusYears(1));
		Double lastYearsPower = this.baseMapper.sumPowerList(energyType, unitNo, lastyears.toString());
		// 环比增长率
		if (yearsPower > 0) {
			Double growthRate = (yearsPower - lastYearsPower) / lastYearsPower * 100; // 增长率
			if (Double.isInfinite(growthRate) || Double.isNaN(growthRate)) {
				map.put("yearsRate", "-");
			} else {
				map.put("yearsRate", new BigDecimal(String.valueOf(growthRate)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
			}
		} else {
			map.put("yearsRate", "-");
		}
		list.add(map);
		return list;
	}

	@Override
	public JSONObject powerLayer(String unitNo, String energyType, String date) {
		JSONObject jsonPower = new JSONObject();
		JSONObject chartData = new JSONObject();
		List<String> xData = new ArrayList<>();
		List<Double> yData1 = new ArrayList<>();//当前
		List<Map<String, Object>> chartPowerList = this.baseMapper.chartYearPower(energyType, unitNo, date);
		for (int m = 1; m < 13; m++) {
			String strMonth = String.format("%02d", m);
			String month = date + strMonth;
			List<Map<String, Object>> chartYearData = chartPowerList.stream().filter(
					bo -> bo.get("timeValue").equals(month))
					.collect(Collectors.toList());
			Double YearData = null;
			if (!chartYearData.isEmpty()) {
				YearData = Double.parseDouble(chartYearData.get(0).get("totalValue").toString());
				yData1.add(YearData);
			} else {
				yData1.add(0.0);
			}
			xData.add(strMonth);
		}
		chartData.put("xData", xData);
		chartData.put("yData1", yData1);
		jsonPower.put("chartData", chartData);//图标
		return jsonPower;
	}

	@Override
	public List<Map<String, Object>> powerSort(String energyType, String date) {
		List<String> idList = new ArrayList<>();//递归后存放的区域id集合
		List<EnergyInput> inputList = this.getBaseMapper().selectList(Wrappers.<EnergyInput>lambdaQuery()
				.eq(EnergyInput::getEnergyType, energyType)
				.groupBy(EnergyInput::getUnitNo));
		if (!inputList.isEmpty()) {
			inputList.forEach(item1 -> {
				idList.add(String.valueOf(item1.getUnitNo()));
			});
		}
		List<Map<String, Object>> resultData = this.baseMapper.powerSortRank(energyType, idList, date.toString().replaceAll("-", ""));
		return powerSortData(inputList,resultData);
	}

	private List<Map<String, Object>> powerSortData(List<EnergyInput> inputList, List<Map<String, Object>> resultData) {
		List<Map<String, Object>> tableData = new ArrayList<>();//表格数据>
		//区域数据累加总和 -计算百分比
		Double totalCount = resultData.stream()
				.mapToDouble(map -> {
					if (map.containsKey("totalValue")) {
						return (Double) map.get("totalValue");
					} else {
						return 0;
					}
				}).sum();
		resultData.forEach(item -> {
			Map<String, Object> map = new HashMap<>();
			if (!item.get("totalValue").toString().equals("0.0") && !item.get("totalValue").toString().equals("0.0")) {
				Double percent = (Double.parseDouble(item.get("totalValue").toString()) / Double.parseDouble(totalCount.toString())) * 100; // 增长率
				map.put("percent", new BigDecimal(percent).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
			} else {
				map.put("percent", "0");
			}
			map.put("incrValue", new BigDecimal(String.valueOf(item.get("totalValue"))).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
			inputList.forEach(item1 -> {
				if (item1.getUnitNo().toString().equals(item.get("unitNo").toString())) {
					map.put("sortName", item1.getUnitName());
					tableData.add(map);
				}
			});
		});
		return tableData;
	}


}